/*
 * @Author: windys
 * @Description: 
 * @Date: 2022-02-11 16:18:38
 */
import axios from 'axios'
import router from '@/router'
import { ElMessage, ElMessageBox } from 'element-plus';
import storage from '@/utils/storage.js'
const server = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  withCredentials: true,
  timeout: 30000
})

let app = null

server.interceptors.request.use(
  config => {
    if (config.app) {
      app = config.app
      app.show()
    }
    if (config.upload) {
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      config.headers['Content-Type'] = 'application/json'
    }
    if (storage.getStorage('token')) {
      config.headers['Authorization'] = 'Bearer ' + storage.getStorage('token')
    }
    if (storage.getStorage('uuid')) {
      config.headers['uuid'] = storage.getStorage('uuid')
    }


    if (config.method === 'post' || config.method === 'put') {
      const requestObj = {
        url: config.url,
        data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
        time: new Date().getTime()
      }
      const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
      const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
      if (requestSize >= limitSize) {
        console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制，无法进行防重复提交验证。')
        return config;
      }

      const sessionObj = sessionStorage.getItem('sessionObj') ? JSON.parse(sessionStorage.getItem('sessionObj')) : null
      console.log(sessionObj, 'xxxx')
      if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
        sessionStorage.setItem('sessionObj', JSON.stringify(requestObj))
      } else {
        const s_url = sessionObj.url;                // 请求地址
        const s_data = sessionObj.data;              // 请求数据
        const s_time = sessionObj.time;              // 请求时间
        const interval = 1000;                       // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = '数据正在处理，请勿重复提交';
          console.warn(`[${s_url}]: ` + message)
          return Promise.reject(new Error(message))
        } else {
          sessionStorage.setItem('sessionObj', JSON.stringify(requestObj))
        }
      }
    }
    config.data
    return config
  },
  error => {
    console.log(error, '请求错误') // for debug
    Toast(error)
    return Promise.reject(error)
  }
)

server.interceptors.response.use(
  response => {
    if (app) {
      setTimeout(() => {
        app.hide()
      }, 1000)
    }
    let res = response.data
    console.log(res, '------')
    if (res.code == 500) {
      ElMessage({
        type: "error",
        message: res.msg,
      })
      return null
    } else if (res.code == 403) {
      ElMessageBox.confirm(
        '登录失效,请重新登录',
        '提示',
        {
          confirmButtonText: '确认',
          showCancelButton: false,
          type: 'warning',
          showClose: false,
          closeOnClickModal: false
        }
      ).then(() => {
        router.push('/login')
      })
    } else if (res.code == 200) {
      if (res.data) {
        return res.data
      } else {
        return res
      }
    } else {
      ElMessage({
        type: "error",
        message: res.msg,
      })
      return null
    }

  },
  error => {
    console.log('请求接口超时', error)
    ElMessage({
      type: 'error',
      message: error.message
    })
    return Promise.reject(error)
  }

)

export default server
